package com.example.testapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 测试Handler的基本使用
1. 创建Handler成员变量对象, 并重写其handleMessage()
2. 在分/主线程创建Message对象
3. 使用handler对象发送Message
4. 在handleMessage()中处理消息
 */
public class HandlerTestActivity extends ApplicationActivity{
    private ProgressBar pb_handler1_loading;
    private EditText et_handler1_result;
    // 1.创建Handler成员变量对象，并重写其handleMessage()
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                // 4. 在handlerMessage() 中处理消息
                String result = (String) msg.obj;
                et_handler1_result.setText(result);
                pb_handler1_loading.setVisibility(View.INVISIBLE);
            }
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler5);

        pb_handler1_loading = (ProgressBar) findViewById(R.id.pb_handler1_loading);
        et_handler1_result = (EditText) findViewById(R.id.et_handler1_result);



    }

    /**
     *  1. 主线程，显示提示视图 （ProgressDialog/ProgressBar）
     *  2. 分线程，联网请求，并得到响应数据
     *  3.主线程，显示数据
     * **/
    // TODO  两种请求方式 有什么优点
    public void getSubmit1(View view){
        // 主线程 显示提示视图
        pb_handler1_loading.setVisibility(View.VISIBLE);  // 控制显示隐藏
        // 2.分线程 联网请求，并得到响应数据
        new Thread(){
            @Override
            public void run() {
                String path = "http://192.168.0.105:8080/example/index.jsp?username=%271231%27&age=12";
                try {
                    final String result = requestToString(path);
                    // 主线程，显示数据
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            et_handler1_result.setText(result);
                            pb_handler1_loading.setVisibility(View.INVISIBLE);
                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }
                super.run();
            }
        }.start();

    }
    public void getSubmit2(View view){
        // 1.主线程 显示提示视图
        pb_handler1_loading.setVisibility(View.VISIBLE);
        // 2.分线程，联网请求，并得到响应数据
        new Thread(){
            @Override
            public void run() {
                super.run();
                String path = "http://192.168.0.105:8080/example/index.jsp?username=%271231%27&age=12";
                try {
                    final String result = requestToString(path);
                    // 分线程创建message对象
                    Message message = Message.obtain();
                    message.what = 1; // 标识
                    message.obj = result;
                    // 3.使用handler对象发送Message
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            et_handler1_result.setText(result);
                            pb_handler1_loading.setVisibility(View.INVISIBLE);
                        }
                    });

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();
    }

    // 请求服务端 得到返回的结果字符串
    // http://192.168.0.105:8080/example/index.jsp?username=%271231%27&age=12 (本地)

    public String requestToString(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            connection.connect();
            InputStream is = connection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            String result = baos.toString();
            connection.disconnect();

            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
